package org.flown.shop.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.flown.shop.dao.OrdersDAO;
import org.flown.shop.entity.Orders;
import org.flown.util.HTTPClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;


@Service
public class OrdersService extends BaseService<Orders>
{
    private final OrdersDAO dao_orders;


    @Autowired
    public OrdersService(OrdersDAO dao) {
        super(dao);
        this.dao_orders = (OrdersDAO)this.dao;
    }


    public Orders getOrdersByID(int id) {return this.selectByID(id);}

    public JsonNode getGoodsByID(int id)
            throws IOException, InterruptedException
    {
        return new ObjectMapper().readTree(HTTPClientUtil.GET("localhost:8080/shop/goods/getGoodsByID?id=" + id, null).body());
    }


    /**
     * goodsID
     * userID
     * sellerID
     * storeID
     * count 默认1
     * address
     * price
     * */
    public int insertOrders(Orders orders) {
        JsonNode goods_json;
        try {
            goods_json = this.getGoodsByID(orders.getGoodsID());
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        if (goods_json == null || goods_json.isEmpty())
            return 0;
        orders.setPrice(goods_json.get("price").floatValue() * orders.getCount());
        return this.insert(orders);
    }
    public boolean updateOrdersByID(Orders original_orders) {return this.updateByID(original_orders);}
    public int deleteOrdersByID(int id) {return this.deleteByID(id);}

    public boolean updateOrdersTrackingNumber(int id, String tracking_number) {return this.dao_orders.updateTrackingNumberByID(id, tracking_number);}

}













